package me.zhengjie.modules.system.rest

import me.zhengjie.logging.annotation.Log
import me.zhengjie.modules.system.domain.Province
import me.zhengjie.modules.system.service.ProvinceService
import me.zhengjie.modules.system.service.dto.ProvinceDTO
import me.zhengjie.modules.system.service.dto.ProvinceQueryCriteria
import io.swagger.v3.oas.annotations.media.Schema
import jakarta.servlet.http.HttpServletResponse
import org.springframework.data.domain.Pageable
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import java.io.IOException

/**
 * @author kuki
 * @date 2022-07-21
 */
@Schema(description = "Province管理")
@RestController
@RequestMapping("/api/province")
class ProvinceController(private val provinceService: ProvinceService) {
    @Log("导出数据")
    @Schema(description = "导出数据")
    @GetMapping(value = ["/download"])
    @PreAuthorize("@el.check('province:list')")
    @Throws(
        IOException::class
    )
    fun download(response: HttpServletResponse?, criteria: ProvinceQueryCriteria?) {
        provinceService.download(provinceService.queryAll(criteria!!) as MutableList<ProvinceDTO>, response)
    }

    @GetMapping
    @Log("查询Province")
    @Schema(description = "查询Province")
    @PreAuthorize("@el.check('province:list')")
    fun getProvinces(criteria: ProvinceQueryCriteria?, pageable: Pageable?): ResponseEntity<*> {
        return ResponseEntity(provinceService.queryAll(criteria!!, pageable), HttpStatus.OK)
    }

    @PostMapping
    @Log("新增Province")
    @Schema(description = "新增Province")
    @PreAuthorize("@el.check('province:add')")
    fun create(@Validated @RequestBody resources: Province?): ResponseEntity<*> {
        return ResponseEntity(provinceService.create(resources!!), HttpStatus.CREATED)
    }

    @PutMapping
    @Log("修改Province")
    @Schema(description = "修改Province")
    @PreAuthorize("@el.check('province:edit')")
    fun update(@Validated @RequestBody resources: Province?): ResponseEntity<*> {
        provinceService.update(resources!!)
        return ResponseEntity<Any?>(HttpStatus.NO_CONTENT)
    }

    @get:PreAuthorize("@el.check('province:list','roles:list')")
    @get:GetMapping(value = ["/provinceTree"])
    @get:Schema(description = "返回全部省市区域")
    val provinceTree: ResponseEntity<*>
        get() = ResponseEntity(provinceService.getProvinceTree(provinceService.getProvincesAll()), HttpStatus.OK)

    @DeleteMapping(value = ["/{id}"])
    @Log("删除Province")
    @Schema(description = "删除Province")
    @PreAuthorize("@el.check('province:del')")
    fun delete(@PathVariable id: Int?): ResponseEntity<*> {
        provinceService.delete(id!!)
        return ResponseEntity<Any?>(HttpStatus.OK)
    }
}